/**
 * 
 */
package com.devmindset.legoframework.client.mvc.binding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;

/**
 * Extension of {@link ListGrid} to provide form-to-model binding.
 * 
 * @author <a href="mailto:ice.penov@devmindset.com">Ice Penov</a>
 */
public class SmartListGrid extends ListGrid {
  
  private Map<ListGridRecord, Model> map = new HashMap<ListGridRecord, Model>();
  
  public void setModels(List<? extends Model> models) {
    List<ListGridRecord> records = new ArrayList<ListGridRecord>();
    for (Model model : models) {
      //convert to record
      ListGridRecord record = new ListGridRecord();
      for (String property : model.getPropertyNames()) {
        record.setAttribute(property, model.get(property));
      }
      map.put(record, model);
      records.add(record);
    }
    setData(records.toArray(new ListGridRecord[0]));
  }
  
  /**
   * Gets the underlying {@link Model} for the
   * corresponding record grid.
   *  
   * @param record the {@link ListGridRecord}
   * 
   * @return the corresponding model
   */
  public Model getUnderlyingModel(ListGridRecord record) {
    Model result = null;
    if (map.containsKey(record)) {
      result = map.get(record);
    }
    return result;
  }    
    
}